package com.zhang.authoritycenter.manager.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zhang.authoritycenter.common.model.dao.auth.FriendRelationDO;
import com.zhang.authoritycenter.common.model.dao.auth.UserBaseDO;
import com.zhang.authoritycenter.common.model.dto.auth.AddFriendReqDTO;
import com.zhang.authoritycenter.common.util.UserUtil;
import com.zhang.authoritycenter.dao.auth.FriendRelationMapper;
import com.zhang.authoritycenter.manager.IFriendRelationManager;
import com.zhang.authoritycenter.service.IUserBaseService;
import com.zhang.infrastructure.model.KingHoodException;
import com.zhang.infrastructure.model.KingHoodExceptionUtil;
import com.zhang.infrastructure.util.base.IdGenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2024-03-18 16:01
 **/
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
@Slf4j
@Service
public class FriendRelationManagerImpl implements IFriendRelationManager {

    private final IUserBaseService userBaseService;
    private final FriendRelationMapper friendRelationMapper;

    @Override
    public Boolean addFriend(AddFriendReqDTO in) {

        Long userId = UserUtil.getUserId();
        KingHoodExceptionUtil.isNull(userId,"当前用户未登录");

        UserBaseDO userBaseDO = userBaseService.getUserBaseDO(in.getUsername());
        KingHoodExceptionUtil.trueThrows(Objects.isNull(userBaseDO) || Objects.isNull(userBaseDO.getId()),"该账号不存在");

        // 检查是否已经是好友
        long count = new LambdaQueryChainWrapper<>(friendRelationMapper)
                .eq(FriendRelationDO::getUserId, userId)
                .eq(FriendRelationDO::getFriendUserId, userBaseDO.getId())
                .count();
        KingHoodExceptionUtil.trueThrows(count>0,"已经加为好友！");

        // 加好友
        FriendRelationDO one = new FriendRelationDO();
        one.setId(IdGenUtil.getId());
        one.setUserId(userId);
        one.setFriendUserId(userBaseDO.getId());
        friendRelationMapper.insert(one);

        return true;
    }

    @Override
    public List<UserBaseDO> getMyFriendList() {

       return  friendRelationMapper.getMyFriendList(UserUtil.getUserId());
    }
}
